import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Role } from '../entities/role.entity';

@Injectable()
export class RoleService {
    constructor(
        @InjectRepository(Role)
        private roleRepository: Repository<Role>,
    ) {}

    async findAll(): Promise<Role[]> {
        return this.roleRepository.find();
    }

    async create(role: Role): Promise<Role> {
        return this.roleRepository.save(role);
    }

    async updateUsername(userId: number, newUsername: string): Promise<Role> {
        const role = await this.roleRepository.findOne({ where: { id: userId } });
        if (!role) {
            throw new NotFoundException(`用户ID ${userId} 不存在`);
        }

        role.username = newUsername;
        return this.roleRepository.save(role);
    }
} 